// pages/teacher/sign_result.js

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  
  data: {
    fpath: null,
    showView: false,
    currentTab: 0,
    signnum: 0,
    unsignnum: 0,
    totalnum: 0,
    userList: [],
    unsignUserList: [],
    // 页面垂直滑动的距离
    scrollTop: undefined,
    unsignTip: true,
    classList: [],
    listName:[],
    listIndex:[],
    selectIndex:[],
    selectList:[],
    loading: {
      type: 'flip',
      show: true,
      size: 'medium',
      color: '#e54d42',
      name: 'flip'
    },
    types: [
      "未认证",
      "旷课",
      "迟到",
      "请假",
      "其他"
    ],
    typeIndex: 0,
    state: '',
    lid: 1,
    signtitle: '软件工程实践',
    myRes:[],
    myUrl:'',
    fname:'',
    listid:''
  },

  onPageScroll(res) {
    this.setData({
      scrollTop: res.scrollTop
    })
  },

  onLoad: async function (options) {
    // 页面初始化 options为页面跳转所带来的参数
   
    this.data.lid = options.lid
    if(options.cname!='undefined'&&options.cname!='null')
    this.setData({
      fname: options.cname
      
    })
    console.log("nnn"+this.data.fname)
    await this.getClassList2()
    await this.getSign()
    await this.getUnsign()
  },

  // 返回已签到结果（教师端）
  async getSign() {
    const {
      data: res
    } = await wx.$http.get('/rec/resultTeacher', {
      lid: this.data.lid
    }, {
      token: true,
      checkToken: true
    })
    if (res.code != 200) {
      wx.showToast({
        title: res.message,
        icon: "none"
      })

    } else {
      console.log("mk",res)
      this.setData({
        signtitle: res.data[0],
        userList: res.data[2],
        signnum: res.data[2].length
      })
    }
  },

  async getUnsign() {
    const {
      data: res
    } = await wx.$http.get('/rec/noSignInTea', {
      lid: this.data.lid
    }, {
      token: true,
      checkToken: true
    })
    if (res.code != 200) {
      // wx.showToast({
      //   title: "获取结果失败",
      //   icon: "none"
      // })
      if (res.code == 197) {
        this.setData({
          unsignTip: false
        })
      }
    } else {
      var total = this.data.signnum
      this.setData({
        unsignUserList: res.data[2],
        unsignnum: res.data[2].length,
        totalnum: total + res.data[2].length
      })
      this.data.myRes=this.data.unsignUserList
      console.log(res.data);
    }
  },
  //改变代签到类型 
  bindTypeChange: function (e) {
    var newstate = this.data.types[e.detail.value]
    this.setData({
      typeIndex: e.detail.value,
      state: newstate
    })
    this.signin(e)
  },
  signin: async function (e) {
    await wx.User.recByTea({
      data: {
        lid: this.data.lid,
        name: e.currentTarget.dataset.name,
        state: this.data.state
      }
    })
    wx.showToast({
      title: wx.getStorageSync('recByTea'),
      icon: 'none'
    })
    await wx.User.contrast({
      data: {
        linkId: this.data.lid,
        listId:this.data.listid
      }
    })
    await this.getSign()
    this.setData({
      unsignUserList: wx.getStorageSync('unSignList'),
      unsignnum: wx.getStorageSync('unSignList').length
    })
  },

  //改变签到类型
  resultTypeChange: async function(e){
    await wx.User.setSignInState({
      data: {
        uid: e.currentTarget.dataset.uid,
        lid: this.data.lid,
        state: this.data.types[e.detail.value]
      },
    })
    await this.getSign()
    this.getUnsign()
  },

  //点击上传获取历史名单
  getClassList: async function () {
    this.setData({
      showView: !this.data.showView
    })
    await wx.User.findClassListByTid({
      data: {
        uid: wx.getStorageSync('userinfo').uid
      },
    })
    this.setData({
      classList: wx.getStorageSync('classList')
    })
  },

getClassList2: async function () {
    await wx.User.findClassListByTid({
      data: {
        uid: wx.getStorageSync('userinfo').uid
      },
    })
    this.setData({
      classList: wx.getStorageSync('classList')
    })
    for(var i=0;i<this.data.classList.list.length;i++){
      this.data.listName.push(this.data.classList.list[i].name)
      this.data.listIndex.push(i)
    }
    this.setData({
      listIndex:this.data.listIndex,
      listName:this.data.listName
    })
    console.log(this.data.listName);
    console.log(this.data.listIndex);
  },
selectList(e){
  var index=e.detail.value
  console.log(index);
  if(this.data.selectIndex.includes(index)==false){
  this.data.selectIndex.push(index)
  this.data.selectList.push(this.data.classList.list[index])
  }                                                                                      console.log(this.data.selectIndex);
  this.setData({
    selectList:this.data.selectList
  })
  console.log(this.data.selectList);
},
  //删除已选名单
  deleteList: async function (e) {
    var index=e.currentTarget.dataset.index
    console.log(e.currentTarget.dataset.index);
    this.data.selectList.splice(index,1)
    this.setData({
      selectList:this.data.selectList
    })
  },

  //对比签到名单
  contrast: async function (e) {
    this.setData({
      showView: !this.data.showView,
      fname:e.currentTarget.dataset.fname
    })
    this.data.listid=e.currentTarget.dataset.listid
    await wx.User.contrast({
      data: {
        linkId: this.data.lid,
        listId:this.data.listid
      }
    })
    await this.getSign()
    this.setData({
      unsignUserList: wx.getStorageSync('unSignList'),
      unsignnum: wx.getStorageSync('unSignList').length
    })
    this.data.myRes=this.data.unsignUserList

    
  },

  //上传新签到名单
  uploadNewFile: function () {
    return new Promise((resolve, reject) => {
      var path;
      var fileName;
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success(res) {
          path = res.tempFiles[0].path
          fileName = res.tempFiles[0].name
          wx.uploadFile({
            url: 'https://www.xqzjgsu.top:8001/class/uploadClassList',
            filePath: path,
            name: 'list',
            header: {
              'content-type': 'multipart/form-data',
              'Authorization': 'Bearar ' + wx.getStorageSync('token')
            },
            formData: {
              uid: wx.getStorageSync('userinfo').uid,
              fileName: fileName
            },
            success: function (res) {
              resolve(true)
              var json = JSON.parse(res.data)
              if (json.code == 200) {
                wx.showToast({
                  title: json.message,
                  icon: "success"
                })
              } else {
                wx.showToast({
                  title: json.message,
                  icon: 'none'
                })
              }
            }
          })
        }
      })
    })

  },
  async upload(){
    var that=this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        console.log(res)
        const path = res.tempFiles[0].path
        let size = res.tempFiles[0].size;
        let filename = res.tempFiles[0].name;
        wx.uploadFile({
          url: 'https://www.xqzjgsu.top:8001/list/excel', //仅为示例，非真实的接口地址
          filePath: path,
          name: 'list',
          header: {
            'content-type': 'multipart/form-data',
            'Authorization': 'Bearar ' + wx.getStorageSync('token')
          },
          formData: {
            uid: wx.getStorageSync('userinfo').uid,
            listName: filename
          },
          success: function(res){
            console.log(res.data)
            var json = JSON.parse(res.data)
            if (json.code == 200) {
              wx.showToast({
                title: json.message,
                icon: "success"
              })
             that.getClassList2()
            } else {
              wx.showToast({
                title: json.message,
                icon: 'none'
              })           
            }           
            //do something
          }
        })  
      }
      })    
  },
  // 下载文件
 excel: function (e) {
    wx.request({
      url:'https://www.xqzjgsu.top:8001/rec/excel',
      data: JSON.stringify({
        lid:this.data.lid,
        noSignIn:this.data.myRes
      }),
      header: {
        "content-type": "application/json",
        'Authorization': `bearer ${wx.getStorageSync("access_token")}`
      },
      method: "POST",
      dataType: "json",
      responseType: "arraybuffer", //注意这里的responseType
      success: (result) => {
        console.log("下载成功！", result)
        var fileManager = wx.getFileSystemManager();
        var FilePath = wx.env.USER_DATA_PATH + "/签到结果.xls";
        fileManager.writeFile({
          data: result.data,
          filePath: FilePath,
          encoding: "binary", //编码方式 
          success: result => {
            wx.openDocument({ //我这里成功之后直接打开
              filePath: FilePath, 
              showMenu:true,
              fileType: "xls",
              success: result => {
                console.log("打开文档成功");
              },
              fail: err => {
                console.log("打开文档失败", err);
              }
            });
            wx.hideLoading();
          },
          fail: res => {
            wx.showToast({
              title: '导出失败!',
              icon: 'none', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
              duration: 2000, //停留时间
            })
            console.log(res);
          }
        })
        wx.hideLoading()
      },
      fail(err) {
        console.log(err)
        wx.hideLoading()
      }
 
    })

  },
downfile(){
  console.log(this.data.lid);
  wx.downloadFile({
    url:'https://www.xqzjgsu.top:8001/rec/excel2?lid=51721262445511754189'+this.data.lid,
    success (res) {
      console.log(res);
        wx.saveFile({
            tempFilePath: res.tempFilePath,
           
        })
    }
})
},

  // wx.downloadFile({
  //   url: 'http://47.103.218.55:8077/fss/rec/excel?lid=' + this.data.lid,
  //   success(res) {
  //     console.log(res)
  //     var savePath = wx.env.USER_DATA_PATH + "/123.xls"
  //     wx.getFileSystemManager()
  //       .saveFile({ 
  //         tempFilePath: res.tempFilePath,
  //         filePath: savePath,
  //         success(res2) {
  //           wx.saveImageToPhotosAlbum({
  //             filePath: savePath,
  //             success: (res) => {
  //               wx.showModal({
  //                 title: '文件已保存到手机相册',
  //                 content: '位于tencent/MicroMsg/WeiXin下 \r\n将保存的文件重命名改为[ .docx ]后缀即可',
  //                 confirmColor: '#0bc183',
  //                 confirmText: '知道了',
  //                 showCancel: false
  //               })
  //             },
  //             fail(res) {
  //               console.log(res)
  //             }
  //           })
  //         },
  //         fail(res) {
  //           console.log(res)
  //         }
  //       })
  //   },
  // })
  //滑动切换
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },

  navtodata() {
    if (this.data.lid == 0) {
      wx.showToast({
        title: 'Error',
      })
      return;
    }
    // wx.navigateTo({
    //   url: './signdata?lid-' + this.data.lid,
    // })
    wx.navigateTo({
      url: './signdata?signnum=' + this.data.signnum + '&unsignnum=' + this.data.unsignnum + '&totalnum=' + this.data.totalnum,
    })
  },


  //点击切换
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
})